<template>
    <div class="app-container">
        <el-card>
            <div class="fs18 fwb mb20">费用数据</div>
            <div class="flex flex ver flex-sb mb40">
                <div>
                    <el-select v-model="waterMachineData" placeholder="请选择区片" size="large" @change="changeSelect"
                        class="w120 mr-10">
                        <el-option label="积分" :value="1"></el-option>
                        <el-option label="物业费" :value="2"></el-option>
                    </el-select>
                </div>

                <div class="flex flex-ver" v-show="waterMachineData == 1">
                    <div class="flex">
                        <div :class="['opt-btn', { active: type == 'month' }]" @click="changeTime('month')">按月</div>
                        <div :class="['opt-btn', { active: type == 'year' }]" @click="changeTime('year')">按年</div>
                    </div>

                    <div v-show="type == 'month'">
                        <el-date-picker v-model="monthData" type="monthrange" range-separator="至"
                            @change="monthDataChange" value-format="yyyy-MM" start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </div>

                    <div v-show="type == 'year'">
                        <el-date-picker v-model="yearsStart" :picker-options="startDatePicker" @change="changeStartYear"
                            value-format="yyyy" type="year" placeholder="开始时间">
                        </el-date-picker>
                        ~
                        <el-date-picker v-model="yearsEnd" value-format="yyyy" @change="changeEndYear"
                            :picker-options="endDatePicker" type="year" placeholder="结束时间">
                        </el-date-picker>
                    </div>
                </div>

                <div v-show="waterMachineData == 2">
                    <div class="flex">
                        <div :class="['opt-btn', { active: selectPriceType == 0 }]"
                            style="width:auto;padding:0 20px;" @click="changePrice(0)">3000元以下</div>
                        <div :class="['opt-btn', { active: selectPriceType == 1 }]"
                            style="width:auto;padding:0 20px;" @click="changePrice(1)">3000元及以上</div>
                    </div>
                </div>

            </div>

            <!-- 图标 -->
            <div id="columnChart"></div>

        </el-card>
    </div>
</template>

<script>
import echarts from "echarts";
import { statisticsAllScores,statisticsPropertyFee } from "@/api/grzq/statistics.js";
export default {
    data() {
        return {
            startYearMonth: '',
            endYearMonth: '',
            selectPriceType: 0,
            waterMachineData: 1,
            type: "month",
            startDatePicker: this.beginDate(),
            endDatePicker: this.processDate(),
            yearsStart: '',
            yearsEnd: '',
            monthData: [],
            rolesList: [{}, {}],
            pgSize: 0, //默认20 每个20条
            ttCount: 0, //返回总条数
            currentPageNumber: 1, //传递的分页page参数
            setTime: [],
        }
    },
    computed: {

    },
    watch: {
        yearsStart(newval) {
            if (newval == null) {
                this.$set(this, 'yearsStart', '')
            }
        },
        yearsEnd(newval) {
            if (newval == null) {
                this.$set(this, 'yearsEnd', '')
            }
        },
        monthData: {
            handler: function (newval) {
                console.log(1111)
                if (newval == null) {
                    this.$set(this, "startYearMonth", "");
                    this.$set(this, "endYearMonth", "");
                } else {
                    this.$set(this, "startYearMonth", newval[0]);
                    this.$set(this, "endYearMonth", newval[1]);
                }
            },
            immediate: true,
            deep: true
        }
    },
    components: {
    },
    created() {
        this.monthData = this.calcCurrentYearMonth();
        this.startYearMonth = this.calcCurrentYearMonth()[0];
        this.endYearMonth = this.calcCurrentYearMonth()[1];
    },
    async mounted() {
        this.columnChart();
        await this.statisticsAllScores();
    },
    methods: {
        async statisticsPropertyFee(){
            const res = await statisticsPropertyFee({
                type: this.selectPriceType,
            });

            this.columnChart({
                xAxis: [
                    {
                        data: res.data.date,
                    },
                ],
                series: res.data.series,
                // series: resRel,
            })
        },
        async statisticsAllScores() {
            const res = await statisticsAllScores({
                // id: this.waterMachineData,
                start_time: this.type == 'month' ? this.startYearMonth : this.yearsStart ? this.yearsStart + '-01' : '',
                end_time: this.type == 'month' ? this.endYearMonth : this.yearsEnd ? this.yearsEnd + '-12' : '',
                type: this.type,
            });

            // 1 初始化echarts时如果低于接口返回的对象数量，择需要加以下代码 保证图表正常显示
            // let resRel = res.data.series;
            // resRel.forEach(i=>{
            //     i.type = 'bar';
            //     i.stack = 'Ad';
            // })

            this.columnChart({
                xAxis: [
                    {
                        data: res.data.date,
                    },
                ],
                series: res.data.series,
                // series: resRel,
            })

        },
        async changeStartYear(e) {
            if (this.$common._empty(this.yearsEnd)) return;
            if (this.$common._empty(e)) return;
            await this.statisticsAllScores();
        },
        async changeEndYear(e) {
            if (this.$common._empty(this.yearsStart)) return;
            if (this.$common._empty(e)) return;
            //切换第二个picker时调用接口
            await this.statisticsAllScores();
        },
        async monthDataChange() {
            // if (this.$common._empty(this.waterMachineData)) {
            //     this.$message.error('请先选择水机');
            //     return;
            // }

            await this.statisticsAllScores();
        },
        calcCurrentYearMonth() {
            let currentYear = this.$common.getCurrentYear();
            let currentMonth = this.$common.getCurrentMonth();
            let realTime = [];
            if (currentMonth > 0 && currentMonth < 10) {
                if (currentMonth == 9) {
                    realTime = [currentYear + '-0' + currentMonth, currentYear + '-' + Number(currentMonth + 1)];
                } else {
                    realTime = [currentYear + '-0' + currentMonth, currentYear + '-0' + currentMonth];
                }

            } else {
                if (currentMonth == 12) {
                    realTime = [currentYear + '-' + Number(currentMonth, currentYear + 1) + '-01'];
                }

            }
            return realTime;
        },
        async changeSelect(e) {
            if (e == 1) {
                // myChart.dispose();
                let myChart = echarts.init(document.getElementById("columnChart"));
                await this.statisticsAllScores();
            } else {
                // myChart.dispose();
                let myChart = echarts.init(document.getElementById("columnChart"));
                //请求另外接口
                await this.statisticsPropertyFee();
            }
        },
        getSum() {

        },
        columnChart(newObj) {
            // 基于准备好的dom，初始化echarts实例
            let myChart = echarts.init(document.getElementById("columnChart"));
            // 绘制图表
            let myOption = {
                color: ["#2AAE67", "#F6DE74"],
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    },
                    formatter: (params) => {
                        // let sumPrice = params.slice(0, 3).reduce((prev, next) => prev + next.value, 0);
                        // let sumCount = params.slice(3, 5).reduce((prev, next) => prev + next.value, 0);
                        // console.log(111, params)
                        let s = "";
                        s += `${params[0].axisValue}` + "\n";
                        // s +=
                        //     `总费用${parseInt(sumPrice)}元` + `   总次数${parseInt(sumCount)}次` + "\n";
                        for (var i = 0; i < params.length; i++) {
                            s += "<div class='flex flex-ver'>";
                            s +=
                                `<div style='margin-right:4px;width:8px;height:8px;background-color:${myOption.color[i]};border-radius:50%'></div>`;
                            s += `<div>${params[i].seriesName}：${params[i].value}${[0, 1, 2].includes(i) ? '元' : '次'}</div>`;
                            s += "</div>";
                        }

                        return s;
                    },
                    extraCssText: "width:220px; white-space:pre-wrap;", //遮罩层整体样式设置
                },
                legend: {
                },//点击切换暂时隐藏 影响移入的显示数据
                grid: {
                    left: "3%",
                    right: "4%",
                    bottom: "3%",
                    containLabel: true,
                },
                xAxis: [
                    {
                        type: "category",
                        data: [
                            "区片12-07",
                            // "区片12-08",
                            // "区片12-09",
                            // "区片12-10",
                        ],
                    },
                ],
                yAxis: [
                    {
                        type: "value",
                    },
                ],
                barWidth: 30,
                series: [
                    {
                        name: "购买人积分",
                        type: "bar",
                        stack: "Ad",
                        emphasis: {
                            focus: "series",
                        },
                        data: [1],
                    },
                    {
                        name: "管理人积分",
                        type: "bar",
                        stack: "Ad", //此属性控制单排，多排显示
                        emphasis: {
                            focus: "series",
                        },
                        data: [2],
                    },
                    // {
                    //     name: "微信1",
                    //     type: "bar",
                    //     stack: "Ad",
                    //     emphasis: {
                    //         focus: "series",
                    //     },
                    //     data: [3, 33, 333, 555],
                    // },
                    // {
                    //     name: "注册2",
                    //     type: "bar",
                    //     stack: "Ad", //此属性控制单排，多排显示
                    //     emphasis: {
                    //         focus: "series",
                    //     },
                    //     data: [4, 44, 444, 5555],
                    // },
                    // {
                    //     name: "注册3",
                    //     type: "bar",
                    //     stack: "Ad", //此属性控制单排，多排显示
                    //     emphasis: {
                    //         focus: "series",
                    //     },
                    //     data: [5, 55, 5555, 55555],
                    // },
                ],
            };

            // if(newObj && newObj.series && (myOption.series.length > newObj.series.length)) myOption.series.slice(newObj.series.length,myOption.series.length);
            Object.assign(myOption, newObj);
            // console.log(555,myOption)
            myChart.setOption(myOption);

            myChart.resize();
        },
        changeTime(type) {
            this.$set(this, 'type', type);
            if (!this.$common._empty(this.waterMachineData)) this.statisticsAllScores();
        },
        async changePrice(type) {
            this.selectPriceType = type;
            await this.statisticsPropertyFee();
        },
        changeYear(e) {
            //切换第二个picker时调用接口
        },
        handleChange(value) {
            console.log(value);
        },

        // 选择年份范围选择时开始时间不能大于结束时间，结束时间不能小于开始时间
        // 提出开始时间必须小于提出结束时间
        beginDate() {
            let self = this
            return {
                disabledDate(time) {
                    if (self.yearsEnd !== '') {
                        let fixedTime = new Date(time)
                        return fixedTime.getFullYear() > self.yearsEnd
                    }
                }
            }
        },
        // 提出结束时间必须大于提出开始时间
        processDate() {
            let self = this
            return {
                disabledDate(time) {
                    // let fixedTime = new Date(self.oldTime).getTime()
                    // return time.getTime() < fixedTime
                    let fixedTime = new Date(time)
                    return fixedTime.getFullYear() < self.yearsStart
                }
            }
        },

        //分页change事件
        pageCurrentChangeEvent(e) {
            // this.currentPageNumber = e;
            // this.$router.push({
            //     query: Object.assign(this.dataForm, { page: e }),
            // });





            // this.getData();//getData
        },
    },
    destroyed() {
    }
}
</script>

<style scoped lang="scss">
.opt-btn {
    width: 60px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 12px;
    border: 1px solid rgb(220, 223, 230);
    cursor: pointer;
}

#columnChart {
    width: 100%;
    height: 400px;
}

.active {
    border-color: #409EFF;
    color: #409EFF;
}
</style>
